package com.dudu.service.impl;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.springframework.beans.BeanUtils;

import com.dudu.bean.MenuBean;
import com.dudu.bean.ParamBean;
import com.dudu.dao.MenuDao;
import com.dudu.model.Menu;
import com.dudu.service.IMenuService;

import core.CoreDao;
import core.CoreDaoInvoke;
/**
 * 菜单service
 * @author gaoxs
 *
 */
public class MenuServiceImpl implements IMenuService {
	private CoreDao coreDao = CoreDaoInvoke.getInstance();
	private MenuDao menuDao = new MenuDao();
	/**
	 * 根据用户ID查询其能查看的权限
	 * @param userId
	 * @return
	 */
	public String getUserMenu(int userId) {
		List<JSONObject> resultList = new ArrayList<JSONObject>();	
		List<Menu> menuList = menuDao.queryUserMenusById(coreDao, userId);
		
		for(Menu menuLevel1 : menuList){
			if(menuLevel1.getTree_level() == 1){
				JSONObject objectLevel1 = new JSONObject();
				objectLevel1.put("menuid", menuLevel1.getId());
				objectLevel1.put("menuname", menuLevel1.getName());
				objectLevel1.put("icon", menuLevel1.getIcon());
				objectLevel1.put("url", null);
				List<JSONObject> childList = new ArrayList<JSONObject>();
				for(Menu menuLevel2 : menuList){
					if(menuLevel2.getTree_level() == 2 && menuLevel2.getParent_id() == menuLevel1.getId()){
						JSONObject objectChild = new JSONObject();
						objectChild.put("menuid", menuLevel2.getId());
						objectChild.put("menuname", menuLevel2.getName());
						objectChild.put("icon", menuLevel2.getIcon());
						objectChild.put("url", menuLevel2.getUrl());
						objectLevel1.put("children", new ArrayList(0));
						
						childList.add(objectChild);
					}
				}
				objectLevel1.put("children", childList);
				
				resultList.add(objectLevel1);
			}
		}
		
		return resultList.toString();
	}
	/**
	 * 查询全部菜单
	 * @return
	 */
	public List<JSONObject> queryAll() {
		return menuDao.queryAll(coreDao);
	}
	/**
	 * 新增菜单
	 * @param bean
	 * @return
	 */
	public int insertMenu(MenuBean bean){
		return menuDao.insert(coreDao, conversion(bean));
	}
	/**
	 * 更新菜单
	 * @param bean
	 * @return
	 */
	public int updateMenu(MenuBean bean){
		return menuDao.update(coreDao, conversion(bean));
	}
	/**
	 * 查询菜单
	 * @param level
	 * @return
	 */
	public List<ParamBean> queryMenuName(int level){
		return menuDao.queryMenuName(coreDao,level);
	}
	/**
	 * 转化
	 * @param menu
	 * @return
	 */
	private MenuBean conversion(Menu menu){
		MenuBean menuBean=new MenuBean();
		BeanUtils.copyProperties(menu, menuBean);//源,目的
		//PropertyUtils.copyProperties(dest, orig);//目的,源
		return menuBean;
	}
	/**
	 * 转化
	 * @param menuBean
	 * @return
	 */
	private Menu conversion(MenuBean menuBean){
		Menu menu=new Menu();
		BeanUtils.copyProperties(menuBean,menu);//源,目的
		//PropertyUtils.copyProperties(dest, orig);//目的,源
		return menu;
	}
}
